<template>
  <div class="chart" ref="chartRef"></div>
</template>

<script lang="ts">
export default {
  name: "PieChart",
};
</script>

<script lang="ts" setup>
import * as echarts from "echarts";
import { ref, watch } from "vue";

const chartRef = ref();

const props = defineProps<{
  data: any;
  title: string;
}>();

watch(props, () => {
  const myEcharts = echarts.init(chartRef.value);

  const data = (props.data.data1 as number[]).map((value, index) => {
    return {
      name: props.data.axisX[index] as string,
      value,
    };
  });

  const total = data.reduce((p, c) => p + c.value, 0);

  const option = {
    title: [
      {
        text: props.title,
      },
      {
        // 主标题
        text: "累计订单量",
        // 副标题
        subtext: total,
        textStyle: {
          fontSize: 16,
        },
        subtextStyle: {
          fontSize: 28,
        },
        left: "center",
        top: "42%",
      },
    ],
    legend: {
      right: "10%",
      top: "middle",
      orient: "vertical",
      formatter: function (name: string) {
        // 查找数据
        const item = data.find((item) => item.name === name) as {
          name: string;
          value: number;
        };
        // (item.value / total) * 100) 得到百分比
        // toFixed 取小数点几位
        const percent = ((item.value / total) * 100).toFixed(2) + "%";
        return name + " " + percent;
      },
    },
    series: {
      type: "pie",
      data,
      // 半径（内半径，外半径）
      radius: [85, 120],
      itemStyle: {
        borderWidth: 2,
        borderColor: "#fff",
      },
    },
  };
  myEcharts.setOption(option);
});
</script>

<style scoped>
.chart {
  width: 100%;
  height: 300px;
}
</style>
